package com.server.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.server.common.QueryPageParam;
import com.server.common.Result;
import com.server.service.GoodsService;
import com.server.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/goods")
public class GoodsController {

	@Autowired
	private GoodsService goodsService;

	@PostMapping("/saveORmodify")
	public Result saveORmodify(@RequestBody Goods goods){
		System.out.println(goods);

		if(goodsService.saveOrUpdate(goods))
			return Result.suc(null, 1L);
		else
			return Result.fail();
	}
	@PostMapping("/delete")
	public Result delete(@RequestBody Map<String, List<Integer>> requestMap){
		boolean res = true;
		List<Integer> ids = requestMap.get("ids");
		for(Integer id : ids){
			if(id!=null)
				res=res&goodsService.removeById(id);
		}
		if(res)
			return Result.suc(null, 1L);
		else
			return Result.fail();
	}

	@PostMapping("/querylike")
	public Result querylike(@RequestBody QueryPageParam query) {


		// 创建分页对象
		Page<Goods> page = new Page<>(query.getPageNum(), query.getPageSize());

		// 获取查询参数
		HashMap<String, Object> map = query.getParam();

		// 创建条件构造器
		LambdaQueryWrapper<Goods> lambdaQueryWrapper = new LambdaQueryWrapper<>();

		// 动态拼接条件
		String id = map.get("id") != null ? map.get("id").toString().trim() : "";
		String name = map.get("name") != null ? map.get("name").toString().trim() : "";


		if (!name.isEmpty()) {
			lambdaQueryWrapper.like(Goods::getName, name);
		}

		if (!id.isEmpty()) {
			lambdaQueryWrapper.eq(Goods::getId, id); // 精确查询
		}

		// 执行查询
		IPage<Goods> res = goodsService.pageC(page, lambdaQueryWrapper);
		// 返回结果
		return Result.suc(res.getRecords(), res.getTotal());
	}
}
